#include "AsioIOServicePool.h"

AsioIOServicePool::AsioIOServicePool(int thread_num)
:_nextIOServiceIndex(0),_ioServices(thread_num)
{
    //初始化work
    //初始化线程
    _works.reserve(thread_num);
    _threads.reserve(thread_num);

    for (size_t i = 0; i < thread_num; i++)
    {
        _works.emplace_back(std::make_unique<Work>(_ioServices[i]));
        _threads.emplace_back([this,i](){
            _ioServices[i].run();
        });
    }
    
    
    
}
AsioIOServicePool::~AsioIOServicePool()
{
    std::cout<<"AsioIOServicePool::~AsioIOServicePool()"<<std::endl;
    Stop();
}
boost::asio::io_context& AsioIOServicePool::GetIOService()
{
    auto& io_service = _ioServices[_nextIOServiceIndex++];
    //判断下标是否大于等于_ioServices.size()
    if(_nextIOServiceIndex >= _ioServices.size())
    {
        _nextIOServiceIndex = 0;
    }
    return io_service;

}
void AsioIOServicePool::Stop()
{
    //清除work
    _works.clear();
    //停止io_service
    for(auto& io_service : _ioServices)
    {
        io_service.stop();
    }
    //回收线程资源
    for(auto& thread : _threads)
    {
        thread.join();
    }

}

